#ifndef BUJIN_H
#define BUJIN_H

#include <math.h>
#include <stdlib.h>
#include "ti_msp_dl_config.h"

// --- 硬件参数 ---
#define STEPS_PER_REVOLUTION 200    // 电机步距角1.8度(360/1.8=200)
#define MICROSTEPS 32               // 驱动器细分数
#define PWM_CLOCK_FREQ 8000000      // PWM时钟频率(Hz)

// --- 系统参数 ---
#define ISR_INTERVAL_S 0.01f       // 中断周期(秒)

// --- 运动参数 ---
#define CONSTANT_SPEED_RPM 60       // 最大恒定转速
#define START_SPEED_RPM 3           // 启动速度
#define ACCELERATION_TIME_MS 100    // 加速时间
#define ACCELERATION_STEPS ((int)(ACCELERATION_TIME_MS / (ISR_INTERVAL_S * 1000)))
#define DECELERATION_TIME_MS 50    // 减速时间
#define DECELERATION_STEPS ((int)(DECELERATION_TIME_MS / (ISR_INTERVAL_S * 1000)))


// --- 限制值 ---
#define MAX_TARGET_SPEED 60   // 最大目标转速(RPM)
#define MIN_TARGET_SPEED 10    // 最小目标转速(RPM)
#define POS_ERROR_LIMIT  90.0f// 最大位置误差(度)

// 全局常量
extern const float PULSES_PER_DEGREE;

// --- X轴PID状态变量声明 ---
extern float pos_error_x;
extern float pos_last_error_x;
extern float pos_integral_x;
extern float pos_output_x;

extern float speed_error_x;
extern float speed_last_error_x;
extern float speed_integral_x;
extern float speed_output_x;
extern float actual_speed_x;

// --- Y轴PID状态变量声明 ---
extern float pos_error_y;
extern float pos_last_error_y;
extern float pos_integral_y;
extern float pos_output_y;

extern float speed_error_y;
extern float speed_last_error_y;
extern float speed_integral_y;
extern float speed_output_y;
extern float actual_speed_y;

// 脉冲计数变量声明
extern long x_pulse_count;
extern long y_pulse_count;

// 电机A状态变量声明
extern float s_ma_current_target_angle;
extern float s_ma_current_assumed_angle;
extern long  s_ma_pulses_remaining;
extern int   s_ma_direction;
extern float s_ma_pulse_accumulator;
extern int   s_ma_acceleration_counter;
extern int   s_ma_decelerate_flag;
extern int   s_ma_deceleration_counter;

// 电机B状态变量声明
extern float s_mb_current_target_angle;
extern float s_mb_current_assumed_angle;
extern long s_mb_pulses_remaining;
extern int s_mb_direction;
extern float s_mb_pulse_accumulator;
extern int s_mb_acceleration_counter;
extern int s_mb_decelerate_flag;
extern int s_mb_deceleration_counter;

// 函数声明
void motor_control_init(void);
int Calculate_target(int Target);
int Calculate_MA_Angle_PWM(float target_angle1);
int Calculate_MB_Angle_PWM(float target_angle);
int X_Axis_PID_Control(float camera_x_error);
int Y_Axis_PID_Control(float camera_y_error);
void Update_Actual_Speed(void);
void Set_PWM(int L_Target, int R_Target);

#endif // BUJIN_H